﻿using System;
using System.Text;
using System.Web.Mvc;
using Xwltz.Framework.Framework;
using Xwltz.Framework.Helper;

namespace Xwltz.Framework.Mvc
{
    public class StandardJsonResult : ActionResult, IStandardResult
    {
        public string ContentType { get; set; }

        #region Implementation of ICustomResult

        public bool Success { get; set; }

        public string Message { get; set; }

        public StandardJsonResult()
        {
            ContentType = "application/json";
        }

        public void Succeed()
        {
            Success = true;
        }

        public void Fail()
        {
            Success = false;
        }

        public void Succeed(string message)
        {
            Success = true;
            Message = message;
        }

        public void Fail(string message)
        {
            Success = false;
            Message = message;
        }

        public void Try(Action action)
        {
            try
            {
                action();
                Succeed();
            }
            catch (KnownException ex)
            {
                Fail(ex.Message);
            }
            catch (Exception ex)
            {
                Fail(ex.GetAllMessages());
            }
        }

        #endregion

        public override void ExecuteResult(ControllerContext context)
        {
            var response = context.HttpContext.Response;
            response.ContentType = ContentType;
            response.ContentEncoding = Encoding.UTF8;
            response.Write(SerializerHelper.ToJson(ToJsonObject()));
        }

        protected virtual IStandardResult ToJsonObject()
        {
            var result = new StandardResult
            {
                Success = Success,
                Message = Message
            };
            return result;
        }
    }

    public class StandardJsonResult<T> : StandardJsonResult, IStandardResult<T>
    {
        public T Value { get; set; }

        protected override IStandardResult ToJsonObject()
        {
            var result = new StandardResult<T>
            {
                Success = Success,
                Message = Message,
                Value = Value
            };
            return result;
        }
    }
}